package com.spring.hot;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Cizai
 * @since 2022/12/02 19:16
 * @see <a href="https://leetcode.cn/problems/generate-parentheses/?favorite=2cktkvj">...</a>
 **/
public class 括号生成 {

    List<String> result = new ArrayList<>();
    StringBuilder str = new StringBuilder();
    public List<String> generateParenthesis(int n) {

        if (n == 1) return Collections.singletonList("()");

        backtrack(n,0,0);
        return result;
    }

    private void backtrack(int n, int left, int right) {
        if (right>left) return;
        if (left == n && right == n) {
            result.add(str.toString());
            return;
        }
        if (left < n) {
            str.append("(");
            backtrack(n,left+1,right);
            str.deleteCharAt(str.length() - 1);
        }
        if (right < n) {
            str.append(")");
            backtrack(n, left, right + 1);
            str.deleteCharAt(str.length() - 1);
        }
    }
}
